<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇:新世界 - 地图导入测试</title>
    
    <!-- Bootstrap CSS -->
    <link href="../plugin/bootstrap-5.3.8-dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="../plugin/bootstrap-icons-1.13.1/font/bootstrap-icons.css" rel="stylesheet">
    <!-- 闯关游戏CSS -->
    <link href="css/challenge-game.css" rel="stylesheet">
    
    <style>
        .test-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            margin-bottom: 20px;
            border-radius: 10px;
        }
        .test-info {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .map-details {
            background: #e9ecef;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .test-controls {
            background: #d4edda;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .status-panel {
            position: fixed;
            top: 20px;
            right: 20px;
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 15px;
            border-radius: 8px;
            z-index: 1000;
            max-width: 300px;
        }
        .coords-panel {
            position: fixed;
            top: 200px;
            right: 20px;
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 15px;
            border-radius: 8px;
            z-index: 1000;
            max-width: 300px;
            font-family: monospace;
            font-size: 12px;
        }
        .coords-item {
            margin: 5px 0;
        }
        .coords-label {
            color: #4fc3f7;
        }
        .coords-value {
            color: #69f0ae;
        }
    </style>
</head>
<body>
    <!-- 状态面板 -->
    <div class="status-panel" id="statusPanel">
        <h6><i class="bi bi-info-circle me-2"></i>测试状态</h6>
        <div id="testStatus">准备开始测试...</div>
    </div>

    <!-- 坐标信息面板 -->
    <div class="coords-panel" id="coordsPanel" style="display: block;">
        <h6><i class="bi bi-geo-alt me-2"></i>实时坐标信息</h6>
        <div class="coords-item">
            <span class="coords-label">地图尺寸:</span> 
            <span class="coords-value" id="mapSize">未知</span>
        </div>
        <div class="coords-item">
            <span class="coords-label">蛇头位置:</span> 
            <span class="coords-value" id="snakeHead">未知</span>
        </div>
        <div class="coords-item">
            <span class="coords-label">障碍物数量:</span> 
            <span class="coords-value" id="obstacleCount">未知</span>
        </div>
        <div class="coords-item">
            <span class="coords-label">地图模式:</span> 
            <span class="coords-value" id="mapMode">未知</span>
        </div>
        <div class="coords-item">
            <span class="coords-label">网格大小:</span> 
            <span class="coords-value" id="gridSize">未知</span>
        </div>
    </div>

    <div class="container-fluid">
        <!-- 测试头部信息 -->
        <div class="test-header">
            <h1 class="text-center">
                <i class="bi bi-map-fill me-2"></i>
                地图导入测试 - 贪吃蛇闯关模式
            </h1>
            <p class="text-center mb-0">测试地图: map_normal_1_800.json</p>
        </div>
        
        <!-- 地图详细信息 -->
        <div class="map-details">
            <h4><i class="bi bi-info-circle me-2"></i>地图配置信息</h4>
            <div class="row">
                <div class="col-md-3">
                    <strong>地图模式:</strong> <span id="detailMapMode">普通模式 (normal)</span>
                </div>
                <div class="col-md-3">
                    <strong>地图尺寸:</strong> <span id="detailMapSize">800 × 800 像素</span>
                </div>
                <div class="col-md-3">
                    <strong>网格大小:</strong> <span id="detailGridSize">20 像素</span>
                </div>
                <div class="col-md-3">
                    <strong>障碍物数量:</strong> <span id="detailObstacleCount">大量障碍物</span>
                </div>
            </div>
        </div>
        
        <!-- 测试控制面板 -->
        <div class="test-controls">
            <h4><i class="bi bi-gear me-2"></i>测试功能</h4>
            <div class="row">
                <div class="col-md-3">
                    <button class="btn btn-primary w-100" onclick="loadEmbeddedMap()">
                        <i class="bi bi-upload me-2"></i>加载地图
                    </button>
                </div>
                <div class="col-md-3">
                    <button class="btn btn-success w-100" onclick="startGame()">
                        <i class="bi bi-play-fill me-2"></i>开始游戏
                    </button>
                </div>
                <div class="col-md-3">
                    <button class="btn btn-warning w-100" onclick="resetGame()">
                        <i class="bi bi-arrow-repeat me-2"></i>重置游戏
                    </button>
                </div>
                <div class="col-md-3">
                    <button class="btn btn-info w-100" onclick="resetMap()">
                        <i class="bi bi-map me-2"></i>重置地图
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 游戏容器 -->
    <div class="game-container">
        <!-- 游戏头部 -->
        <div class="game-header">
            <h1 class="game-title">
                <i class="bi bi-flag-fill me-2"></i>
                闯关模式 - 地图测试
            </h1>
            <div class="level-info" id="levelInfo">关卡 1 / 3</div>
        </div>
        
        <!-- 游戏内容区域 -->
        <div class="game-content">
            <!-- 游戏画布区域 -->
            <div class="game-area">
                <div class="game-canvas-container">
                    <canvas id="gameCanvas" width="600" height="600"></canvas>
                </div>
                
                <!-- 移动端控制按钮 -->
                <div class="mobile-controls">
                    <div></div>
                    <button class="control-btn" id="mobileUp">↑</button>
                    <div></div>
                    <button class="control-btn" id="mobileLeft">←</button>
                    <button class="control-btn" id="pauseBtnMobile">⏸️</button>
                    <button class="control-btn" id="mobileRight">→</button>
                    <div></div>
                    <button class="control-btn" id="mobileDown">↓</button>
                    <div></div>
                </div>
                
                <!-- 游戏结束/关卡完成遮罩 -->
                <div class="game-overlay" id="gameOverlay" style="display: none;">
                    <div class="overlay-content">
                        <h2 class="overlay-title" id="overlayTitle">游戏结束</h2>
                        <p class="overlay-message" id="overlayMessage">您的贪吃蛇撞到了墙壁！</p>
                        
                        <div class="overlay-stats" id="overlayStats">
                            <div class="stat-item">
                                <span class="stat-label">当前分数：</span>
                                <span class="stat-value" id="finalScore">0</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">最高分数：</span>
                                <span class="stat-value" id="highScore">0</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">当前关卡：</span>
                                <span class="stat-value" id="finalLevel">1</span>
                            </div>
                        </div>
                        
                        <div class="overlay-buttons">
                            <button class="btn-overlay btn-overlay-success" id="restartBtn">
                                <i class="bi bi-arrow-repeat me-2"></i>重新开始
                            </button>
                            <button class="btn-overlay" id="nextLevelBtn" style="display: none;">
                                <i class="bi bi-arrow-right me-2"></i>下一关
                            </button>
                            <button class="btn-overlay btn-overlay-danger" id="menuBtnOverlay">
                                <i class="bi bi-house me-2"></i>返回主页
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 游戏控制面板 -->
            <div class="game-panel">
                <!-- 小地图和统计信息 -->
                <div class="mini-map-container">
                    <div class="mini-map-header">
                        <i class="bi bi-map me-2"></i>小地图
                    </div>
                    <canvas id="miniMapCanvas" width="120" height="120"></canvas>
                </div>
                
                <!-- 统计信息 -->
                <div class="stats-panel">
                    <div class="stat-item">
                        <span class="stat-label">
                            <i class="bi bi-star-fill me-2"></i>分数：
                        </span>
                        <span class="stat-value" id="scoreValue">0</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-label">
                            <i class="bi bi-trophy-fill me-2"></i>关卡：
                        </span>
                        <span class="stat-value" id="levelValue">1</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-label">
                            <i class="bi bi-arrow-right-square-fill me-2"></i>长度：
                        </span>
                        <span class="stat-value" id="snakeLengthValue">3</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-label">
                            <i class="bi bi-clock-fill me-2"></i>时间：
                        </span>
                        <span class="stat-value" id="timeValue">00:00</span>
                    </div>
                </div>
                
                <!-- 关卡进度 -->
                <div class="level-progress">
                    <div class="stat-item">
                        <span class="stat-label">关卡进度：</span>
                        <span class="stat-value" id="levelProgress">0%</span>
                    </div>
                    <div class="progress-bar">
                        <div class="progress-fill" id="progressFill" style="width: 0%"></div>
                    </div>
                    <div class="stat-item">
                        <span class="stat-label">目标分数：</span>
                        <span class="stat-value" id="targetScore">100</span>
                    </div>
                </div>
                
                <!-- 控制按钮 -->
                <div class="controls-panel">
                    <div class="control-buttons">
                        <button class="btn-game btn-start" id="startBtn">
                            <i class="bi bi-play-fill me-2"></i>开始游戏
                        </button>
                        <button class="btn-game btn-pause" id="pauseBtn">
                            <i class="bi bi-pause-fill me-2"></i>暂停
                        </button>
                        <button class="btn-game" id="resetBtn">
                            <i class="bi bi-arrow-repeat me-2"></i>重新开始
                        </button>
                        <button class="btn-game" id="menuBtn">
                            <i class="bi bi-house me-2"></i>返回主页
                        </button>
                    </div>
                </div>
                
                <!-- 游戏说明 -->
                <div class="game-instructions">
                    <div class="instructions-title">
                        <i class="bi bi-keyboard me-2"></i>操作说明
                    </div>
                    <ul class="instructions-list">
                        <li><i class="bi bi-arrow-up"></i>W / ↑ : 向上移动</li>
                        <li><i class="bi bi-arrow-down"></i>S / ↓ : 向下移动</li>
                        <li><i class="bi bi-arrow-left"></i>A / ← : 向左移动</li>
                        <li><i class="bi bi-arrow-right"></i>D / → : 向右移动</li>
                        <li><i class="bi bi-space"></i>空格键 : 暂停/继续</li>
                        <li><i class="bi bi-r-square"></i>R键 : 重新开始</li>
                        <li><i class="bi bi-escape"></i>ESC键 : 返回主页</li>
                    </ul>
                </div>
            </div>
        </div>
        
        <!-- 游戏底部 -->
        <div class="game-footer">
            <a href="map-test.html" class="back-btn">
                <i class="bi bi-arrow-left me-2"></i>重新测试
            </a>
        </div>
    </div>

    <!-- 测试脚本 -->
    <script>
        // 简化的地图数据（绕过CORS限制）
        const embeddedMapData = {
            "mode": "normal",
            "width": 800,
            "height": 800,
            "gridSize": 20,
            "elements": {
                "obstacles": [
                    {"x": 240, "y": 120, "type": "obstacle"},
                    {"x": 140, "y": 140, "type": "obstacle"},
                    {"x": 140, "y": 260, "type": "obstacle"},
                    {"x": 520, "y": 140, "type": "obstacle"},
                    {"x": 620, "y": 160, "type": "obstacle"},
                    {"x": 620, "y": 240, "type": "obstacle"},
                    {"x": 140, "y": 540, "type": "obstacle"},
                    {"x": 120, "y": 660, "type": "obstacle"},
                    {"x": 220, "y": 660, "type": "obstacle"},
                    {"x": 540, "y": 640, "type": "obstacle"},
                    {"x": 640, "y": 640, "type": "obstacle"},
                    {"x": 660, "y": 540, "type": "obstacle"},
                    {"x": 640, "y": 520, "type": "obstacle"},
                    {"x": 620, "y": 520, "type": "obstacle"},
                    {"x": 620, "y": 540, "type": "obstacle"},
                    {"x": 620, "y": 560, "type": "obstacle"},
                    {"x": 640, "y": 560, "type": "obstacle"},
                    {"x": 640, "y": 540, "type": "obstacle"},
                    {"x": 660, "y": 540, "type": "obstacle"},
                    {"x": 640, "y": 540, "type": "obstacle"}
                ]
            }
        };
        
        // 加载嵌入的地图数据
        function loadEmbeddedMap() {
            console.log('开始加载嵌入的地图数据');
            
            // 检查challenge-game.js中的applyMapConfig函数是否存在
            if (typeof applyMapConfig === 'function') {
                console.log('应用地图配置...');
                applyMapConfig(embeddedMapData);
                
                // 显示加载成功消息
                if (typeof showOverlay === 'function') {
                    showOverlay('地图加载成功', `已加载 ${embeddedMapData.mode} 模式地图 (${embeddedMapData.width}×${embeddedMapData.height})`);
                }
                
                console.log('嵌入地图加载完成');
            } else {
                console.error('applyMapConfig函数未找到');
                alert('地图加载功能未初始化，请确保challenge-game.js已正确加载');
            }
        }
        
        let coordUpdateInterval = null;
        
        function updateStatus(message, type = 'info') {
            const statusDiv = document.getElementById('testStatus');
            const typeClass = {
                'info': 'text-info',
                'success': 'text-success',
                'warning': 'text-warning',
                'danger': 'text-danger'
            }[type] || 'text-info';
            
            statusDiv.innerHTML = `<span class="${typeClass}">${message}</span>`;
            console.log(`[${type.toUpperCase()}] ${message}`);
        }
        
        function updateCoords() {
            try {
                // 确保坐标面板可见
                const coordsPanel = document.getElementById('coordsPanel');
                if (coordsPanel.style.display === 'none') {
                    coordsPanel.style.display = 'block';
                }
                
                // 检查游戏状态是否存在
                if (window.gameState) {
                    // 更新地图尺寸
                    const mapSize = document.getElementById('mapSize');
                    if (gameState.currentMap) {
                        mapSize.textContent = `${gameState.currentMap.width || '未知'} × ${gameState.currentMap.height || '未知'}`;
                    } else {
                        // 计算默认地图的实际网格尺寸
                        const gridCount = gameConfig.worldSize / gameConfig.gridSize;
                        mapSize.textContent = `默认地图 (${gridCount} × ${gridCount} 网格)`;
                    }
                
                    // 更新蛇头位置
                    const snakeHead = document.getElementById('snakeHead');
                    if (gameState.snake && gameState.snake.length > 0) {
                        const head = gameState.snake[0];
                        snakeHead.textContent = `(${Math.round(head.x)}, ${Math.round(head.y)})`;
                    } else {
                        snakeHead.textContent = '未知';
                    }
                    
                    // 更新障碍物数量
                    const obstacleCount = document.getElementById('obstacleCount');
                    if (gameState.obstacles && gameState.obstacles.length > 0) {
                        obstacleCount.textContent = gameState.obstacles.length;
                    } else {
                        obstacleCount.textContent = '0';
                    }
                    
                    // 更新地图模式
                    const mapMode = document.getElementById('mapMode');
                    if (gameState.currentMap && gameState.currentMap.mode) {
                        mapMode.textContent = gameState.currentMap.mode;
                    } else {
                        mapMode.textContent = '默认模式';
                    }
                    
                    // 更新网格大小
                    const gridSize = document.getElementById('gridSize');
                    if (gameState.currentMap && gameState.currentMap.gridSize) {
                        gridSize.textContent = `${gameState.currentMap.gridSize}px`;
                    } else {
                        gridSize.textContent = '20px';
                    }

                    // 更新地图详细信息区域
                    const detailMapMode = document.getElementById('detailMapMode');
                    const detailMapSize = document.getElementById('detailMapSize');
                    const detailGridSize = document.getElementById('detailGridSize');
                    const detailObstacleCount = document.getElementById('detailObstacleCount');
                    
                    if (detailMapMode) {
                        detailMapMode.textContent = window.gameState.currentMap ? '自定义地图' : '普通模式 (normal)';
                    }
                    
                    if (detailMapSize) {
                        if (window.gameState.currentMap) {
                            detailMapSize.textContent = `${window.gameState.currentMap.width * (window.gameConfig?.gridSize || 20)} × ${window.gameState.currentMap.height * (window.gameConfig?.gridSize || 20)} 像素`;
                        } else {
                            detailMapSize.textContent = `${window.gameConfig?.worldSize || 800} × ${window.gameConfig?.worldSize || 800} 像素`;
                        }
                    }
                    
                    if (detailGridSize) {
                        detailGridSize.textContent = `${window.gameConfig?.gridSize || 20} 像素`;
                    }
                    
                    if (detailObstacleCount) {
                        if (window.gameState.currentMap) {
                            const obstacleCount = window.gameState.currentMap.obstacles?.length || 0;
                            detailObstacleCount.textContent = `${obstacleCount} 个障碍物`;
                        } else {
                            detailObstacleCount.textContent = '大量障碍物';
                        }
                    }
                } else {
                    // 如果游戏状态不存在，显示默认值
                    const mapSize = document.getElementById('mapSize');
                    // 使用实际的游戏配置值
                    if (window.gameConfig) {
                        // 如果有当前地图，使用地图的格子数；否则使用游戏配置的格子数
                        if (window.gameState && window.gameState.currentMap) {
                            const gridCountX = Math.floor(window.gameState.currentMap.width / window.gameState.currentMap.gridSize);
                            const gridCountY = Math.floor(window.gameState.currentMap.height / window.gameState.currentMap.gridSize);
                            mapSize.textContent = `自定义地图 (${gridCountX} × ${gridCountY} 网格)`;
                        } else {
                            const gridCountX = gameConfig.gridCountX || Math.floor(gameConfig.worldSize / gameConfig.gridSize);
                            const gridCountY = gameConfig.gridCountY || Math.floor(gameConfig.worldSize / gameConfig.gridSize);
                            mapSize.textContent = `默认地图 (${gridCountX} × ${gridCountY} 网格)`;
                        }
                    } else {
                        mapSize.textContent = '默认地图 (60 × 60 网格)';
                    }
                    
                    const snakeHead = document.getElementById('snakeHead');
                    snakeHead.textContent = '未知';
                    
                    const obstacleCount = document.getElementById('obstacleCount');
                    obstacleCount.textContent = '0';
                    
                    const mapMode = document.getElementById('mapMode');
                    mapMode.textContent = '默认模式';
                    
                    const gridSize = document.getElementById('gridSize');
                    gridSize.textContent = '20px';
                }
            } catch (error) {
                console.log('坐标更新错误:', error);
            }
        }
        
        function startCoordUpdates() {
            if (coordUpdateInterval) {
                clearInterval(coordUpdateInterval);
            }
            coordUpdateInterval = setInterval(updateCoords, 500); // 每500ms更新一次
        }
        
        function stopCoordUpdates() {
            if (coordUpdateInterval) {
                clearInterval(coordUpdateInterval);
                coordUpdateInterval = null;
            }
        }
        
        function loadMap(mapFilePath = 'js/data/map/snake_map_normal_1.json') {
            try {
                updateStatus('正在加载地图...', 'info');
                
                // 检查loadMap函数是否存在
                if (typeof window.loadMap === 'function') {
                    window.loadMap(mapFilePath);
                    updateStatus('地图加载成功！', 'success');
                    
                    // 启动坐标更新
                    setTimeout(() => {
                        startCoordUpdates();
                        updateStatus('坐标监控已启动', 'info');
                    }, 1000);
                } else {
                    throw new Error('地图加载功能未找到');
                }
                
            } catch (error) {
                updateStatus('地图加载失败: ' + error.message, 'danger');
            }
        }
        
        function startGame() {
            try {
                updateStatus('正在启动游戏...', 'info');
                
                if (typeof window.startGame === 'function') {
                    window.startGame();
                    updateStatus('游戏已启动！', 'success');
                    
                    // 启动坐标更新
                    setTimeout(() => {
                        startCoordUpdates();
                        updateStatus('坐标监控已启动', 'info');
                    }, 1000);
                } else {
                    throw new Error('游戏启动功能未找到');
                }
                
            } catch (error) {
                updateStatus('游戏启动失败: ' + error.message, 'danger');
            }
        }
        
        function resetGame() {
            try {
                updateStatus('正在重置游戏...', 'info');
                
                if (typeof window.resetGame === 'function') {
                    window.resetGame();
                    updateStatus('游戏已重置！', 'success');
                } else {
                    throw new Error('游戏重置功能未找到');
                }
                
            } catch (error) {
                updateStatus('游戏重置失败: ' + error.message, 'danger');
            }
        }
        
        function resetMap() {
            try {
                updateStatus('正在重置地图...', 'info');
                
                if (typeof window.resetMap === 'function') {
                    window.resetMap();
                    updateStatus('地图已重置！', 'success');
                } else {
                    throw new Error('地图重置功能未找到');
                }
                
            } catch (error) {
                updateStatus('地图重置失败: ' + error.message, 'danger');
            }
        }
        
        // 页面加载完成后自动加载地图
        window.addEventListener('load', function() {
            updateStatus('页面加载完成，准备测试地图导入功能...', 'info');
            
            // 立即显示坐标面板
            const coordsPanel = document.getElementById('coordsPanel');
            if (coordsPanel) {
                coordsPanel.style.display = 'block';
            }
            
            // 立即启动坐标更新
            startCoordUpdates();
            updateStatus('坐标监控已启动', 'info');
            
            // 检查URL参数，如果有地图参数则自动加载
            const urlParams = new URLSearchParams(window.location.search);
            const mapFile = urlParams.get('map');
            
            if (mapFile) {
                // 等待游戏完全初始化后再加载地图
                const waitForGameInit = setInterval(() => {
                    if (typeof window.loadMap === 'function' && typeof window.startGame === 'function') {
                        clearInterval(waitForGameInit);
                        
                        setTimeout(() => {
                            // 使用URL参数中的地图文件路径
                            window.loadMap(mapFile);
                            updateStatus('通过URL参数加载地图成功！', 'success');
                            
                            setTimeout(() => {
                                startGame();
                            }, 2000);
                        }, 1000);
                    }
                }, 100);
                
                // 设置超时，防止无限等待
                setTimeout(() => {
                    clearInterval(waitForGameInit);
                    updateStatus('游戏初始化超时，请手动加载地图', 'warning');
                }, 5000);
            }
        });
    </script>

    <!-- 障碍物渲染器 -->
    <script src="js/obstacle-renderer.js"></script>
    
    <!-- 闯关游戏JavaScript -->
    <script src="js/challenge-game.js"></script>
</body>
</html>